/* The MIT License (MIT)

	Copyright (c) 2013 Schpitt <schpitt@gmail.com>
	https://code.google.com/p/updator/

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE. */

#include "MainWindow.h"
#include "medias.h"

#include <SFML/Graphics.hpp>
#include <SFML/Window.hpp>



MainWindow::MainWindow( sf::RenderWindow* p_window ):
	window(p_window), 
	total_size(0),
	total_progress(0),
	total_files_number(0),
	total_files_number_progress(0),
	file_current_size(0),
	file_current_progress(0),
	second_counter(0),
	bytes_for_this_second(0),
	terminated(false)
{
}

//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

MainWindow::~MainWindow() 
{
}

//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

void MainWindow::init()
{
	// background
	if (!image_backgroung.loadFromMemory( (char*)background_data, 4728 ) )
		printf("[disp] logo not loaded");
	sprite_image_backgroung.setTexture(image_backgroung);

	// text
	if (!font.loadFromMemory( (char*)font_data, 34640 ) ) {
		printf("[disp] font not found");
	} 
	title.setString("Updator");
	title.setFont(font);
	title.setCharacterSize(60);
	title.setPosition(400,10);
	title.setColor(sf::Color(150,150,150) );

	file_current_progress_text.setString("File : [0 / 0]");
	file_current_progress_text.setFont(font);
	file_current_progress_text.setCharacterSize(20);
	file_current_progress_text.setPosition(50,510);
	file_current_progress_text.setColor(sf::Color(50,50,50) );

	total_progress_text.setString("Total : [0 / 0]");
	total_progress_text.setFont(font);
	total_progress_text.setCharacterSize(20);
	total_progress_text.setPosition(50,540);
	total_progress_text.setColor(sf::Color(50,50,50) );

	file_current_name.setString("-");
	file_current_name.setFont(font);
	file_current_name.setCharacterSize(20);
	file_current_name.setPosition(50,480);
	file_current_name.setColor(sf::Color(200,200,200) );

	speed_text.setString("Speed : 0 kB/s");
	speed_text.setFont(font);
	speed_text.setCharacterSize(20);
	speed_text.setPosition(50,570);
	speed_text.setColor(sf::Color(250,250,250) );
	
	file_number_text.setString("0/0");
	file_number_text.setFont(font);
	file_number_text.setCharacterSize(20);
	file_number_text.setPosition(50,450);
	file_number_text.setColor(sf::Color(250,250,250) );

	message_text.setString("");
	message_text.setFont(font);
	message_text.setCharacterSize(20);
	message_text.setPosition(50,400);
	message_text.setColor(sf::Color(250,250,250) );

	refresh();

}

//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

void MainWindow::refresh()
{
	window->clear();
	window->draw(sprite_image_backgroung);
	window->draw(title);
	window->draw(file_current_progress_text);
	window->draw(total_progress_text);
	window->draw(file_current_name);
	window->draw(speed_text);
	window->draw(file_number_text);
	window->draw(message_text);
	window->display();
}

//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

bool MainWindow::update( float p_frametime )
{
	while(!command_queue.empty()) {
		mutex.lock();
		Command command = command_queue.front();
		command_queue.pop();
		mutex.unlock();

		switch(command.cmd) {
			case CONNECTED: {
				printf("[disp] CONNECTED\r\n");
				if(command.data.simple_bool) {
					message_text.setString("Connected ! Downloading hashfile...");
				} else {
					message_text.setString("Cannot connect !");
				}
			} break;
			case DISCONNECTED: {
				if(command.data.simple_bool) {
					printf("[disp] DISCONNECTED OK\r\n");
					message_text.setString("Update successfully finished");
					terminated = true;
				} else {
					printf("[disp] DISCONNECTED NOT OK ! \r\n");
					message_text.setString("Update failed");
				}
			} break;
			case ADD_FILE_DOWNLOAD: {
				printf("[disp] ADD_FILE_TO_DOWNLOAD (size%d)\r\n", command.data.simple_int);
				total_files_number++;
				total_size += command.data.simple_int;
				char tmp[1050];
				sprintf(tmp, "[%d/%d]", total_files_number_progress, total_files_number);
				file_number_text.setString(tmp);
			} break;
			case BEGIN_FILE: {
				printf("[disp] BEGIN_FILE (fn[%s])(size%d)\r\n", command.data.begin_file.filename, command.data.begin_file.size);
				message_text.setString("Downloading files...");
				file_current_progress = 0;
				file_current_size = command.data.begin_file.size;
				total_files_number_progress += 1;
				char tmp[1050];
				sprintf(tmp, "%.1024s", command.data.begin_file.filename);
				file_current_name.setString(tmp);
				
				sprintf(tmp, "[%d/%d]", total_files_number_progress, total_files_number);
				file_number_text.setString(tmp);
			} break;
			case END_FILE: {
				if(command.data.simple_bool) {
					printf("[disp] END_FILE OK\r\n");
				} else {
					printf("[disp] END_FILE NOT OK\r\n");
					total_progress -= file_current_progress;
					file_current_progress = 0;
					total_files_number_progress -= 1;
				}
			} break;
			case DOWNLOAD: {
				//printf("[disp] DOWNLOAD (size%d)\r\n", command.data.simple_int);
				file_current_progress += command.data.simple_int;
				total_progress += command.data.simple_int;
				bytes_for_this_second += command.data.simple_int;
			} break;
			default:
				printf("[disp] unknown (%d)\r\n", command.cmd);
		}
	}
	{
		char tmp[128];

		sprintf(tmp, "File : %ld %c [%ld / %ld]", (file_current_size==0)?0:(int)(((float)file_current_progress / (float)file_current_size)*100), '%', file_current_progress, file_current_size );
		file_current_progress_text.setString(tmp);

		sprintf(tmp, "Total : %ld %c [%ld / %ld]", (total_size==0)?0:(int)(((float)total_progress / (float)total_size)*100), '%', total_progress, total_size );
		total_progress_text.setString(tmp);
		
		second_counter += p_frametime;
		if(second_counter > 1) {
			sprintf(tmp, "Speed : %6.3f kB/s", (second_counter==0)?0.0f:(bytes_for_this_second / (second_counter*1000)) );
			speed_text.setString(tmp);
			second_counter = 0;
			bytes_for_this_second = 0;
		}
	}

	refresh();

	return true;
}

//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

void MainWindow::connected( bool p_success ) 
{
	Command cmd;
	cmd.cmd = CONNECTED;
	cmd.data.simple_bool = p_success;
	mutex.lock();
	command_queue.push(cmd);
	mutex.unlock();
}

//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
 
void MainWindow::updateEnd( bool p_ok ) 
{
	Command cmd;
	cmd.cmd = DISCONNECTED;
	cmd.data.simple_bool = p_ok;
	mutex.lock();
	command_queue.push(cmd);
	mutex.unlock();
}

//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

void MainWindow::executeBegin( const char* p_filename, unsigned int p_size ) 
{
	Command cmd;
	cmd.cmd = BEGIN_FILE;
	cmd.data.begin_file.size = p_size;
	sprintf(cmd.data.begin_file.filename, "%.1024s", p_filename);
	mutex.lock();
	command_queue.push(cmd);
	mutex.unlock();
}

//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

void MainWindow::executeEnd( bool p_success ) 
{
	Command cmd;
	cmd.cmd = END_FILE;
	cmd.data.simple_bool = p_success;
	mutex.lock();
	command_queue.push(cmd);
	mutex.unlock();
}

//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
 
void MainWindow::executeProgress( unsigned int p_size ) 
{
	Command cmd;
	cmd.cmd = DOWNLOAD;
	cmd.data.simple_int = p_size;
	mutex.lock();
	command_queue.push(cmd);
	mutex.unlock();
}

//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

void MainWindow::addToExecute( unsigned long p_size )
{
	Command cmd;
	cmd.cmd = ADD_FILE_DOWNLOAD;
	cmd.data.simple_int = p_size;
	mutex.lock();
	command_queue.push(cmd);
	mutex.unlock();
}

//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

